<template>
  <div>
    <el-card class="sur-card">
      <div class="sur-card-title" slot="header">
        <span
          >正在为<span style="color: red;"
            >[{{ itemName }} | {{ skuName }}]</span
          >设置样本</span
        >
        <el-button type="primary" size="small" @click="showAddRowDialog"
          >添加样本</el-button
        >
      </div>
      <el-row>
        <div class="search-section">
          <el-form :inline="true">
            <el-form-item>
              <el-select size="small" v-model="pageVo.brandId" placeholder="请选择品牌">
                <el-option
                  v-for="brand in brands"
                  :key="brand.id"
                  :label="brand.brandName"
                  :value="brand.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-input size="small" placeholder="请输入型号"> </el-input>
            </el-form-item>
            <el-form-item>
              <el-button-group>
                <el-button size="small" icon="el-icon-search" @click="onSearch"
                  >查询</el-button
                >
                <el-button
                  size="small"
                  icon="el-icon-refresh"
                  @click="onClearSearchForm"
                  >刷新</el-button
                >
              </el-button-group>
            </el-form-item>
          </el-form>
        </div>
      </el-row>
      <el-table :data="samples" border v-loading="loadingTable" size="small">
        <el-table-column
          label="序号"
          type="index"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="brandName"
          label="品牌"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="modelName"
          label="型号"
          align="center"
        ></el-table-column>
        <el-table-column prop="effectImg" label="客户效果图" align="center">
          <template slot-scope="scope">
            <el-image
              fit="cover"
              :preview-src-list="Array.of(scope.row.effectImg)"
              :src="scope.row.effectImg"
              style="height:100px;width: 100px;"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="prodImg" label="实际生产图" align="center">
          <template slot-scope="scope">
            <el-image
              fit="contain"
              :preview-src-list="Array.of(scope.row.prodImg)"
              :src="scope.row.prodImg"
              style="height:100px;width: 100px;"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button type="primary" @click="onEditRow(scope.row)"
              >编辑
            </el-button>
            <el-button type="danger" @click="onDeleteRow(scope.row)"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row>
        <el-pagination
          class="page-section"
          background
          @current-change="onPaging"
          :page-size="pageVo.size"
          @size-change="handleSizeChange"
          :page-sizes="[20, 50, 100, 200]"
          layout="total,sizes,prev, pager, next"
          :total="pageVo.total"
        />
      </el-row>
    </el-card>
    <!--    编辑row对话框-->
    <el-dialog title="编辑样本" :visible.sync="editRowVisible">
      <el-form :model="sampleModel" label-position="left" label-width="120px">
        <el-form-item label="适用型号">
          <el-cascader
            v-model="sampleModel.brandModelIds"
            size="small"
            @change="onModelChange"
            :show-all-levels="false"
            :options="brandModels"
            :props="{ multiple: false, children: 'models' }"
            collapse-tags
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="客户效果图">
          <el-upload
            style="display: inline-block;"
            :http-request="handleEffectImgUploadFile"
            :show-file-list="false"
          >
            <el-button size="small" type="primary" icon="el-icon-picture"
              >点击上传</el-button
            >
          </el-upload>
          <el-avatar
            style="margin-top: 10px;height: 100px;width: 100px;display: flex;justify-content: center;"
            v-if="sampleModel.effectImg"
            shape="square"
            size="100"
            fit="contain"
            :src="sampleModel.effectImg"
          ></el-avatar>
        </el-form-item>
        <el-form-item label="生产图片">
          <el-upload
            style="display: inline-block;"
            :http-request="handleProdImgUploadFile"
            :show-file-list="false"
          >
            <el-button size="small" type="primary" icon="el-icon-picture"
              >点击上传</el-button
            >
          </el-upload>
          <el-avatar
            style="margin-top: 10px;height: 100px;width: 100px;display: flex;justify-content: center;"
            v-if="sampleModel.prodImg"
            shape="square"
            size="100"
            fit="contain"
            :src="sampleModel.prodImg"
          ></el-avatar>
        </el-form-item>
        <el-form-item label="适用模具">
          <el-select
            v-model="sampleModel.moldId"
            filterable
            placeholder="请选择"
          >
            <el-option-group
              v-for="moldGroup in moldGroups"
              :key="moldGroup.brandId"
              :label="moldGroup.brandName"
            >
              <el-option
                v-for="mold in moldGroup.molds"
                :key="mold.id"
                :label="mold.moldName"
                :value="mold.id"
              >
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRowVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSaveRow">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  addItemSample,
  getItemSampleByPage,
  removeItemSampleById,
  updateItemSampleById
} from "@/api/admin-api/SkuSampleApi";
import { getBrandByPage, getBrandModelsTree } from "@/api/admin-api/BrandApi";
import {
  getUploadItemMediaToken,
  uploadFileToAliOss
} from "@/api/admin-api/FileApi";
import { getMoldGroup } from "@/api/admin-api/MbCaseMoldApi";

export default {
  props: {
    itemId: [],
    itemName: [],
    skuName: [],
    skuId: []
  },
  name: "ItemSample",
  data() {
    return {
      brands: [],
      brandModels: [],
      moldGroups: [
        {
          label: "苹果",
          options: [
            { value: 1, label: "苹果12Pro玻璃壳" },
            { value: 2, label: "苹果12Pro软磨砂" },
            { value: 3, label: "苹果X玻璃壳" }
          ]
        },
        {
          label: "华为",
          options: [
            { value: 3, label: "华为P30黑色软磨砂" },
            { value: 4, label: "华为P30玻璃壳" },
            { value: 6, label: "华为P30黄色透明软壳" }
          ]
        }
      ],
      sampleModel: {
        id: null,
        itemId: null,
        skuId: null,
        modelId: null,
        brandId: null,
        effectImg: null,
        prodImg: null,
        moldId: "",
        brandModelIds: []
      },
      samples: [],
      pageVo: {
        current: 1,
        size: 20,
        total: 0, //总数量
        pages: 0, //总页数
        orders: [{ column: "create_time" }], //排序字段
        brandId: "",
        modelName: ""
      },
      editRowVisible: false,
      loadingTable: false
    };
  },
  methods: {
    handleEffectImgUploadFile({ file }) {
      getUploadItemMediaToken().then(uploadToken => {
        // 上传文件
        const formData = new FormData();
        const fileKey = uploadToken.dir.concat(file.name);
        formData.append("key", fileKey);
        formData.append("policy", uploadToken.policy);
        formData.append("OSSAccessKeyId", uploadToken.ossAccessKeyId);
        formData.append("success_action_status", "200");
        formData.append("signature", uploadToken.signature);
        formData.append("file", file);
        // 上传至阿里云oss
        this.$loading();
        console.log("上传地址", uploadToken.fileHost);
        uploadFileToAliOss(uploadToken.fileHost, formData)
          .then(() => {
            this.sampleModel.effectImg =
              "https://asset.fanghaowu.com/" + fileKey;
            this.$loading().close();
          })
          .catch(() => {
            this.$loading().close();
          });
      });
    },
    handleProdImgUploadFile({ file }) {
      getUploadItemMediaToken().then(uploadToken => {
        // 上传文件
        const formData = new FormData();
        const fileKey = uploadToken.dir.concat(file.name);
        formData.append("key", fileKey);
        formData.append("policy", uploadToken.policy);
        formData.append("OSSAccessKeyId", uploadToken.ossAccessKeyId);
        formData.append("success_action_status", "200");
        formData.append("signature", uploadToken.signature);
        formData.append("file", file);
        // 上传至阿里云oss
        this.$loading();
        console.log("上传地址", uploadToken.fileHost);
        uploadFileToAliOss(uploadToken.fileHost, formData)
          .then(() => {
            this.sampleModel.prodImg = "https://asset.fanghaowu.com/" + fileKey;
            this.$loading().close();
          })
          .catch(() => {
            this.$loading().close();
          });
      });
    },
    onModelChange(values) {
      if (values && values.length > 0) {
        this.sampleModel.brandId = values[0];
        this.sampleModel.modelId = values[1];
      }
    },
    loadModelsTree() {
      getBrandModelsTree().then(data => {
        console.log("modelsTree", data);
        this.brandModels = data;
      });
    },
    loadBrands() {
      getBrandByPage({ size: 200 }).then(data => {
        this.brands = data.records;
      });
    },
    onPaging(currentPage) {
      // 页码改变
      this.pageVo.current = currentPage;
      this.loadSamples();
    },
    handleSizeChange(val) {
      //页大小改变
      this.pageVo.size = val;
      this.loadSamples();
    },
    onSaveRow() {
      //保存或更新
      if (this.sampleModel.id) {
        //更新
        this.$loading();
        updateItemSampleById(this.sampleModel)
          .then(() => {
            this.$message.success("操作成功");
            this.loadSamples();
            this.$loading().close();
            this.editRowVisible = false;
          })
          .catch(() => {
            this.$loading().close();
          });
      } else {
        //保存
        this.$loading();
        addItemSample(this.sampleModel)
          .then(() => {
            this.$message.success("操作成功");
            this.$loading().close();
            this.loadSamples();
            this.editRowVisible = false;
          })
          .catch(() => {
            this.$loading().close();
          });
      }
    },
    loadSamples() {
      this.loadingTable = true;
      getItemSampleByPage(this.pageVo)
        .then(data => {
          this.samples = data.records;
          this.pageVo.current = data.current;
          this.pageVo.pages = data.pages;
          this.pageVo.total = Number(data.total);
          this.loadingTable = false;
        })
        .catch(() => {
          this.loadingTable = false;
        });
    },
    onEditRow(row) {
      //编辑行
      this.sampleModel = row;
      this.sampleModel.brandModelIds = [row.brandId, row.modelId];
      this.editRowVisible = true;
    },
    onDeleteRow(row) {
      //删除行
      this.$confirm("确定要删除当前行吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      }).then(() => {
        this.$loading();
        removeItemSampleById(row.id)
          .then(() => {
            this.loadSamples();
            this.$loading().close();
          })
          .catch(() => {
            this.$loading().close();
          });
      });
    },
    showAddRowDialog() {
      //显示添加行对话框
      this.editRowVisible = true;
      this.sampleModel = this.$options.data().sampleModel;
      this.sampleModel.itemId = this.itemId;
      this.sampleModel.skuId = this.skuId;
    },
    onSearch() {
      this.loadSamples();
    },
    onClearSearchForm() {
      this.pageVo = this.$options.data().pageVo;
      this.loadSamples();
    },
    loadBrandGroup() {
      getMoldGroup().then(data => {
        this.moldGroups = data;
      });
    }
  },
  mounted() {
    this.loadSamples();
    this.loadBrands();
    this.loadModelsTree();
    this.loadBrandGroup();
  }
};
</script>

<style scoped></style>
